package com.talent.jiwen_teacher.http.common;


import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * @date 创建时间：2017/8/5
 * @author cmw
 * @description
 */

public class RetrofitCache {
    /**
     * @param fromNetwork
     * @param forceRefresh 是否强制刷新
     * @param <T>
     * @return
     */

    public static <T> Observable<T> load( Observable<T> fromNetwork, boolean forceRefresh) {

        Observable<T> fromCache = Observable.create(new Observable.OnSubscribe<T>() {
            @Override
            public void call(Subscriber<? super T> subscriber) {
                    subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
        //强制刷新
        if (forceRefresh) {
            return fromNetwork;
        } else {
            return Observable.concat(fromCache, fromNetwork).takeFirst(new Func1<T, Boolean>() {
                @Override
                public Boolean call(T t) {
                    return t != null;
                }
            });
        }
    }

}
